package com.cas.controller;

import com.cas.handler.MyAuthenticationHandler;
import com.cas.util.CodeDrawUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

import static com.cas.action.CaptchaAction.CAPTCHA_KEY;
import static com.cas.util.CodeDrawUtil.IMG_HEIGHT;
import static com.cas.util.CodeDrawUtil.IMG_WIDTH;

@Controller
@RequestMapping(value = "captcha")
public class CaptchaController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyAuthenticationHandler.class);

    @RequestMapping(value = "/get",method = RequestMethod.GET,produces = "image/jpg")
    public ModelAndView getCaptcha(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        try {
            this.getRandomCode(request, response);// 输出图片方法
        } catch (Exception e) {
            LOGGER.error("获取验证码异常",e);
        }
        return null;
    }

    /**
     * 生成随机图片
     */
    public void getRandomCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();

        BufferedImage offImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_BGR);
        Graphics2D g2 = offImage.createGraphics();

        CodeDrawUtil codeDrawUtil = new CodeDrawUtil(g2);
        codeDrawUtil.drawImg(IMG_WIDTH, IMG_HEIGHT)
                .drawEclipse(300)
                .drawLine(50)
                .drawFont(4)
                .dispose();
        session.removeAttribute(CAPTCHA_KEY);
        session.setAttribute(CAPTCHA_KEY, codeDrawUtil.getCaptcha());

        ImageIO.write(offImage, "JPEG", response.getOutputStream());// 将内存中的图片通过流动形式输出到客户端
    }

}
